<template>
  <div class="right-panel">
    <div class="title">
      <span>未来{{ futureCountDay }}日 天气概况</span>
    </div>
    <div class="view">
      <div class="left" id="echarts"></div>
      <div class="right">
        <div class="item">
          <span>平均最高气温</span>
          <span>{{ avgMaxTemperature }}℃</span>
        </div>
        <div class="item">
          <span>平均最低气温</span>
          <span>{{ avgMinTemperature }}℃</span>
        </div>

        <!-- 动态生成天气统计项 -->
        <div class="item" v-for="(count, weather) in weatherCounts" :key="weather">
          <span>{{ weather }}天数</span>
          <span>{{ count }}</span>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { onMounted, onUnmounted, ref, watchEffect } from 'vue'
import { useWeatherStore } from '@/stores/weather'
import { charts, type IData } from './options'
import type { ILocationData } from '@/types/weather'

const WeatherStore = useWeatherStore()
const AllWether = ref<ILocationData>()

// 最高温度总和
const max_temperature = ref<number>(0)
// 最低温度总和
const min_temperature = ref<number>(0)
// 未来天数
const futureCountDay = ref<number>(0)

// 平均最高温度和最低温度
const avgMaxTemperature = ref<number>(0)
const avgMinTemperature = ref<number>(0)

// 天气统计（使用 computed 属性动态计算）
const weatherCounts = ref<Record<string, number>>({})

// 图表数据
const chartData = ref<IData[]>([])

// 重置统计变量
function resetStats() {
  max_temperature.value = 0
  min_temperature.value = 0
  futureCountDay.value = 0
  avgMaxTemperature.value = 0
  avgMinTemperature.value = 0
  weatherCounts.value = {}
  chartData.value = []
}

watchEffect(() => {
  // 重置统计数据
  resetStats()

  // 更新当前天气数据
  AllWether.value = WeatherStore.currentLocation

  if (AllWether.value?.future?.daily) {
    // 设置未来天数
    futureCountDay.value = AllWether.value.future.daily.length

    // 遍历每日数据并统计
    AllWether.value.future.daily.forEach((item) => {
      // 累加温度
      max_temperature.value += Number(item.tempMax)
      min_temperature.value += Number(item.tempMin)

      // 统计天气类型
      const weather = item.textDay
      if (weatherCounts.value[weather]) {
        weatherCounts.value[weather] += 1
      } else {
        weatherCounts.value[weather] = 1
      }
    })

    // 计算平均温度（如果有数据）
    if (futureCountDay.value > 0) {
      avgMaxTemperature.value = Number((max_temperature.value / futureCountDay.value).toFixed(1))
      avgMinTemperature.value = Number((min_temperature.value / futureCountDay.value).toFixed(1))
    }

    // 准备图表数据
    chartData.value = Object.entries(weatherCounts.value).map(([name, value]) => ({
      name,
      value,
    }))

    // 更新图表
    charts.updateChart(chartData.value)
  }
})
// 节流函数，防止频繁触发resize
let resizeTimer: number | null = null
onMounted(() => {
  charts.initChart([])
  // 添加窗口大小变化监听器
  window.addEventListener('resize', handleResize)
})
// 处理窗口大小变化
function handleResize() {
  if (resizeTimer) {
    window.clearTimeout(resizeTimer)
  }
  resizeTimer = window.setTimeout(() => {
    charts.resizeChart()
  }, 100)
}

// 移除事件监听器
onUnmounted(() => {
  if (resizeTimer) {
    window.clearTimeout(resizeTimer)
  }
  window.removeEventListener('resize', handleResize)
})
</script>
<style scoped lang="scss">
@use '@/assets/customVar.scss' as *;

.right-panel {
  display: flex;
  flex-direction: column;
  padding: $padding;
  background: rgba(255, 255, 255, 0.45);
  backdrop-filter: blur(10px);
  border-radius: 10px;
  border: 1px solid rgba(255, 255, 255, 0.18);
  box-shadow: $box-shadow;
  // margin-top: var(--margin-top);
  min-width: 25rem;
  .view {
    display: flex;
    flex-direction: row;
    height: 100%;
    .left {
      min-width: 6.25rem;
      min-height: 6.25rem;
      height: 100%;
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .right {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 20px;
      .item {
        display: flex;
        flex-direction: column;
        align-items: center;
        // 如果想让项目中的文本不换行
        span {
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
    }
  }
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .right-panel {
    padding: 1rem 1.5rem;

    .view {
      .left {
        width: 120px;
      }

      .right {
        gap: 15px;
      }
    }
  }
}

@media (max-width: 768px) {
  .right-panel {
    padding: 1rem;

    .title {
      font-size: 16px;
      margin-bottom: 1rem;
    }

    .view {
      flex-direction: column;

      .left {
        width: 100%;
        height: 100px;
        margin-bottom: 1rem;
      }

      .right {
        grid-template-columns: repeat(3, 1fr);
        gap: 12px;

        .item {
          span {
            font-size: 12px;
          }
        }
      }
    }
  }
}
</style>
